package psmanager.swing;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;

import psmanager.PSMain;
import psmanager.db.DBManager;
import psmanager.db.types.Osoba;
import psmanager.swing.action.Actions;
import psmanager.swing.image.ImageUtils;
import psmanager.swing.model.OsobaModel;

import com.nilo.plaf.nimrod.NimRODLookAndFeel;

public class SwingMain extends JFrame {
	private static final long serialVersionUID = -4892451123812832880L;
	
	private final DBManager dbm;
	
	public SwingMain(final DBManager dbm) {
		this.dbm = dbm;
		
		NimRODLookAndFeel NimRODLF = new NimRODLookAndFeel();

		// NimRODLookAndFeel.setCurrentTheme(SSMUMain.makeNimrodTheme());
		
		try {
			UIManager.setLookAndFeel(NimRODLF);
		} catch (Exception Ignorable) { }
		
//		try {
//			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//		} catch (Exception Ignorable) { }
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation(100, 100);
		setSize(screenSize.width-200, screenSize.height-200);
		setMaximizedBounds(GraphicsEnvironment.
				getLocalGraphicsEnvironment().getMaximumWindowBounds());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				dbm.cleanUp();
			}
		});
		setTitle("Model zatvora");
		
		Actions.createActions(dbm);
		ImageUtils.loadIconsAndComponents();
		
		initGUI();
	}
	
	/**
	 * GUI Initialization...
	 */
	@SuppressWarnings({ "serial", "unchecked" })
	private void initGUI() {
		
		final SwingMain tmpRef = this;
		
		createMenus();
		
		setLayout(new BorderLayout());
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		add(tabbedPane, BorderLayout.CENTER);
		
		JPanel personelManager = new JPanel(new BorderLayout());
		tabbedPane.add("Osobe", personelManager);
		
		JPanel recordManager = new JPanel(new BorderLayout());
		tabbedPane.add("Adrese", recordManager);
		
		final JTable osobaTable = new CoolTable(
				new OsobaModel((List<Osoba>) dbm.grabAllByClass(Osoba.class), dbm));
		osobaTable.setShowGrid(true);
		personelManager.add(new JScrollPane(osobaTable), BorderLayout.CENTER);
		final JPanel statusPanel = new JPanel(new BorderLayout());
		final JLabel statusLabel = new JLabel("Prikazano " + osobaTable.getModel().getRowCount() + " osoba.");
		statusPanel.add(statusLabel, BorderLayout.WEST);
		
		// Sorting columns...
		
		final JTableHeader tableHeader = osobaTable.getTableHeader();
		tableHeader.setReorderingAllowed(false);
		tableHeader.addMouseListener( new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if(osobaTable.getModel() instanceof OsobaModel) {
					OsobaModel model = (OsobaModel) osobaTable.getModel();
					int col = tableHeader.columnAtPoint(e.getPoint());
					model.sortByColumn(col);
					osobaTable.repaint();
				}
			}
		});

		
		JPanel buttonsPanel = new JPanel();
		buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
		
		
		// Buttons...
		
		final JButton addButton = new JButton();
		final JButton delButton = new JButton();
		final JButton editButton = new JButton();
		final JButton viewButton = new JButton();
		
		buttonsPanel.add(viewButton);
		buttonsPanel.add(editButton);
		buttonsPanel.add(new JLabel(" | "));
		buttonsPanel.add(delButton);
		buttonsPanel.add(addButton);
		
		
		statusPanel.add(buttonsPanel, BorderLayout.EAST);
		statusPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
		personelManager.add(statusPanel, BorderLayout.SOUTH);
		
		// JTable employeeTable = new JTable(new EmployeeModel(dbm));
		
		JPanel vertiSearchPanel = new JPanel();
		vertiSearchPanel.setBorder(BorderFactory.createTitledBorder("Search"));
		vertiSearchPanel.setLayout(new BoxLayout(vertiSearchPanel, BoxLayout.Y_AXIS));
		personelManager.add(vertiSearchPanel, BorderLayout.NORTH);
		
		JPanel searchPanel1 = new JPanel();
		searchPanel1.setLayout(new BoxLayout(searchPanel1, BoxLayout.X_AXIS));
		vertiSearchPanel.add(searchPanel1);
		
		JPanel searchPanel2 = new JPanel();
		searchPanel2.setLayout(new BoxLayout(searchPanel2, BoxLayout.X_AXIS));
		
		JPanel searchTmpPanel = new JPanel(new BorderLayout());
		searchTmpPanel.add(searchPanel2, BorderLayout.WEST);
		vertiSearchPanel.add(searchTmpPanel);
		
		searchPanel1.add(new JLabel("JMBG: "));
		final JTextField jmbgField = new JTextField();
		searchPanel1.add(jmbgField);
		searchPanel1.add(new JLabel(" Tip: "));
		final JComboBox tipCombo = new JComboBox(
				new String[] {"Svi", "Zatvorenik", "Čuvar", "Doktor"});
		searchPanel1.add(tipCombo);
		searchPanel1.add(new JLabel(" Ime: "));
		final JTextField nameField = new JTextField();
		searchPanel1.add(nameField);
		searchPanel1.add(new JLabel(" Prezime: "));
		final JTextField surnameField = new JTextField();
		searchPanel1.add(surnameField);
		searchPanel1.add(new JLabel(" Adresa: "));
		final JTextField addressField = new JTextField();
		searchPanel1.add(addressField);
		searchPanel1.add(new JLabel(" Dob: "));
		final JTextField ageField = new JTextField();
		searchPanel1.add(ageField);
		JPanel spacePanel = new JPanel();
		spacePanel.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0));
		searchPanel1.add(spacePanel);
		
		
		searchPanel2.add(new JLabel("Sortiraj po: "));
		final JComboBox sortCombo = new JComboBox(
				new String[] {"Nesortirano", "JMBG", "Ime", "Prezime", "Adresa", "Dob"});
		searchPanel2.add(sortCombo);
		
		final JComboBox sortCombo2 = new JComboBox(
				new String[] {"Uzlazno", "Silazno"});
		searchPanel2.add(sortCombo2);
		
		
		// Buttons...
		
		Action searchAction = new AbstractAction("Pretraga!") {
			public void actionPerformed(ActionEvent event) {
				try {
					int age = -1;
					if(!ageField.getText().equals("")) age = Integer.valueOf(ageField.getText());
					osobaTable.setModel(new OsobaModel(dbm.grabOsobeByAtrributesSorted(jmbgField.getText(), 
							tipCombo.getSelectedItem().toString(), nameField.getText(), 
							surnameField.getText(), addressField.getText(), age, 
							sortCombo.getSelectedItem().toString(), sortCombo2.getSelectedItem().toString().equals("Uzlazno")), dbm));
					statusLabel.setText("Prikazano " + osobaTable.getModel().getRowCount() + " osoba.");
				} catch (NumberFormatException e) {
					JOptionPane.showMessageDialog(PSMain.mainFrame, 
							"Dob nije dobro unešena!", "Pogrešan unos!", JOptionPane.ERROR_MESSAGE);
				}
			}
		};
		searchAction.putValue(Action.SHORT_DESCRIPTION, "Pretraži.");
		searchAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_ENTER));
		searchAction.putValue(Action.ACCELERATOR_KEY, 
			KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, ActionEvent.CTRL_MASK));
		final JButton searchButton = new JButton(searchAction);
		
		searchPanel1.add(searchButton);
		
		
		Action addAction = new AbstractAction("Dodaj") {
			public void actionPerformed(ActionEvent event) {
				new CoolDialog(PSMain.mainFrame, dbm, osobaTable, CoolDialog.TYPE_ADD).setVisible(true);
			}
		};
		addAction.putValue(Action.SHORT_DESCRIPTION, "Dodaj novu osobu.");
		addAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_D));
		addAction.putValue(Action.ACCELERATOR_KEY, 
			KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));

		
		
		Action delAction = new AbstractAction("Izbriši") {
			public void actionPerformed(ActionEvent event) {
				int rowIndex = osobaTable.getSelectedRow();
				
				if(rowIndex != -1) {
					TableModel model = osobaTable.getModel();
					if(model instanceof OsobaModel) {
						OsobaModel modelOsobe = (OsobaModel) model;
						String jmbg = modelOsobe.getValueAt(
								rowIndex, 0).toString();
						
						dbm.deleteOsoba(jmbg);
						
						// searchButton.doClick();
						
						// The standard search procedure...
						searchButton.doClick();
					}
					
					
				} else {
					JOptionPane.showMessageDialog(tmpRef,
							"Nijedna osoba nije označena!",
							"Pogreška kod brisanja",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		};
		delAction.putValue(Action.SHORT_DESCRIPTION, "Izbriši osobu iz baze.");
		delAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_I));
		delAction.putValue(Action.ACCELERATOR_KEY, 
			KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));

		
		Action viewAction = new AbstractAction("Pogledaj") {
			public void actionPerformed(ActionEvent event) {
				
				int rowIndex = osobaTable.getSelectedRow();
				
				if(rowIndex != -1) {
					
					// Otvori prozor za pregled
					new CoolDialog(PSMain.mainFrame, dbm, osobaTable, CoolDialog.TYPE_VIEW).setVisible(true);
					
				} else {
					JOptionPane.showMessageDialog(tmpRef,
							"Nijedna osoba nije označena!",
							"Pogreška kod brisanja",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		};
		viewAction.putValue(Action.SHORT_DESCRIPTION, "Pogledaj detaljni profil osobe.");
		viewAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_P));
		viewAction.putValue(Action.ACCELERATOR_KEY, 
			KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));

		
		Action editAction = new AbstractAction("Uredi") {
			public void actionPerformed(ActionEvent event) {
				// TODO
				// Novi prozor za unosenje/uredivanje s postavljenim vrijednostima
				
				int rowIndex = osobaTable.getSelectedRow();
				
				if(rowIndex != -1) {
					
					// Otvori prozor za uredivanje
					new CoolDialog(PSMain.mainFrame, dbm, osobaTable, CoolDialog.TYPE_EDIT).setVisible(true);
					
				} else {
					JOptionPane.showMessageDialog(tmpRef,
							"Nijedna osoba nije označena!",
							"Pogreška kod brisanja",
							JOptionPane.ERROR_MESSAGE);
				}
				
				
			}
		};
		editAction.putValue(Action.SHORT_DESCRIPTION, "Uredi profil osobe.");
		editAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_U));
		editAction.putValue(Action.ACCELERATOR_KEY, 
			KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));

		addButton.setAction(addAction);
		delButton.setAction(delAction);
		editButton.setAction(editAction);
		viewButton.setAction(viewAction);
		
	}
	
	/**
	 * Menus Creation.
	 */
	private void createMenus() {
		
		JMenuBar menuBar = new JMenuBar();
		
		JMenu menuFile = new JMenu("File");
		
		menuFile.addSeparator();
		
		JMenuItem exitMenuItem = new JMenuItem(Actions.getAction("Exit"));
		// exitMenuItem.setIcon(ImageUtils.getIcon("exitSim"));
		menuFile.add(exitMenuItem);
		
		menuBar.add(menuFile);
		
		JMenu menuHelp = new JMenu("Help");
		
		menuBar.add(menuHelp);
		
		setJMenuBar(menuBar);
	}

}
